package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.domain.Region;
import com.share.device.mapper.RegionMapper;
import com.share.device.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService
{
    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<Region> treeSelect(String code) {
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Region::getParentCode, code);
        List<Region> regionList = baseMapper.selectList(wrapper);

        //判断是否有下一层数据，如果有HasChildren=true，否则false
        //把HasChildren遍历，得到每一个Region
        if (!CollectionUtils.isEmpty(regionList)) {
            //查询每个regin对象是否有下一层数据
            regionList.forEach(item -> {
                LambdaQueryWrapper<Region> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Region::getParentCode,item.getCode());
                Long count = baseMapper.selectCount(wrapper1);
                //如果有设置HasChildren=true，否则false
                if (count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }
            });
        }

        return regionList;
    }

}